package org.totoro.boot.extend;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.support.HttpRequestWrapper;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 *
 */
@Configuration
public class Config {

    private static final Logger logger = LoggerFactory.getLogger(Config.class);

    /**
     * 启用负载均衡，启用LoadBalanced 后，restTemplate 只能通过服务名称进行调用，其他例如url 地址进行调用会报错
     *
     * @return
     */
    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {

        RestTemplate restTemplate = new RestTemplate();

        /**
         * 添加  restTemplate 拦截器
         */
        restTemplate.getInterceptors().add(new ClientHttpRequestInterceptor() {
            @Override
            public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {

                /**
                 * 使用包装类，进行扩展
                 */
                HttpRequestWrapper requestWrapper = new HttpRequestWrapper(httpRequest);

                requestWrapper.getHeaders().add("custom-header", "自定义头信息");

                logger.info("into restTemplate ClientHttpRequestInterceptor ");

                return clientHttpRequestExecution.execute(requestWrapper, bytes);

            }
        });

        return restTemplate;
    }

//    @Bean
//    public IRule getCustomRule(){
//        return new CustomRule();
//    }

}
